package udpchatdemo01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 模拟控制台发送消息，接收端展示接收消息
 *
 * 接收端
 */
public class UdpRecieveDemo01 {
    public static void main(String[] args) throws IOException {
        // 创建接收端 socket
        DatagramSocket socket = new DatagramSocket(6666);

        // 一直聊天，知道对方说bye的时候，结束聊天
        while(true){
            // 准备接收数据的空包裹
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);

            // 阻塞式接收包裹
            socket.receive(packet);

            // 接收到信息是bye的时候，结束聊天，断开连接
            String receiveDate = new String(packet.getData(),0,packet.getLength());
            System.out.println(receiveDate);

            if (receiveDate.equals("bye")){
                break;
            }
        }
        // 关闭链接
        socket.close();
    }
}
